package com.hfzy.ihk.web.freeswitchManage.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hfzy.ihk.facade.freeswitchManage.enums.*;
import com.hfzy.ihk.facade.freeswitchManage.service.ReceiveEquipmentService;
import com.hfzy.ihk.web.freeswitchManage.biz.EquipmentInfoBiz;
import com.hfzy.ihk.web.freeswitchManage.constant.RedisKeys;
import com.hfzy.ihk.web.freeswitchManage.support.swx.SwxEquipmentControlProcess;
import com.hfzy.ihk.web.freeswitchManage.vo.EquimentInfo;
import com.hfzy.ihk.web.freeswitchManage.vo.EquimentSlotInfo;
import com.hfzy.ihk.web.freeswitchManage.vo.RedisData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * czs
 * Created by YANFA on 2019/3/27.
 */
@Service(version = "1.0.0")
@Slf4j
public class ReceiveEquipmentServiceImpl implements ReceiveEquipmentService {

    @Autowired
    private EquipmentInfoBiz equipmentInfoBiz;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private SwxEquipmentControlProcess swxEquipmentControlProcess;

    /**
     * 处理设备推送的消息
     * @param swxInfoType
     * @param data
     * @return
     */
    @Override
    public String fsCallReceiveSwxEquipmentInfo(SwxInfoTypeEnum swxInfoType, String data) {
        String rs = "1";
        try {
            JSONObject json = JSON.parseObject(data);
            String sn  = json.getString("server_id");
            JSONObject dataJson = json.getJSONObject("data");
            switch (swxInfoType){
                case MACHINE:
                    log.info(">开始处理设备信息消息{}",data);
                    EquimentInfo equimentInfo = new EquimentInfo();

                    if(dataJson.containsKey("TotalChannels")) {
                        String totalChannels = dataJson.getString("TotalChannels");
                        equimentInfo.setChannelNumber(Integer.valueOf(totalChannels));
                    }

                    equimentInfo.setEquipmentDealer(EquipmentEnum.SWX);
                    equimentInfo.setSn(sn);

                    equipmentInfoBiz.createEquipment(equimentInfo);

                    break;
                case CHANGE_SOLT:
                    log.info(">开始处理卡槽变更消息{}",data);
                    if(!dataJson.containsKey("Channel")||!dataJson.containsKey("SlotID")||!dataJson.containsKey("Info")){
                        return "-1";
                    }

                    String channel = dataJson.getString("Channel");
                    String slotID = dataJson.getString("SlotID");
                    String info = dataJson.getString("Info");

                    EquimentSlotInfo equimentSlotInfo = new EquimentSlotInfo();
                    equimentSlotInfo.setSn(sn);
                    equimentSlotInfo.setChannel(channel);
                    equimentSlotInfo.setSlotId(slotID);
                    if("insert".equals(info)){//插卡但是可能并没有使用并没有在激活状态
                        equimentSlotInfo.setStatus(CardStatusEnum.UP);

                    }else if("remove".equals(info)){//拨卡
                        equimentSlotInfo.setStatus(CardStatusEnum.DOWN);

                    }else {
                        log.info(">swx未识别成功的插拔卡信息{}",data);
                        return "-1";
                    }
                    equipmentInfoBiz.createSolt(equimentSlotInfo);
                    break;
                 case ACTIVE_CARD:
                     log.info(">开始处理激活卡槽消息{}",data);
                     if(!dataJson.containsKey("Channel")||!dataJson.containsKey("SlotID")||!dataJson.containsKey("CCID")){
                         return "-1";
                     }
                     String tchannel = dataJson.getString("Channel");
                     String tslotID = dataJson.getString("SlotID");
                     String ccid = dataJson.getString("CCID");

                     EquimentSlotInfo equimentSlotInfo1 = new EquimentSlotInfo();
                     equimentSlotInfo1.setCcid(ccid);
                     equimentSlotInfo1.setChannel(tchannel);
                     equimentSlotInfo1.setSlotId(tslotID);
                     equimentSlotInfo1.setSn(sn);
                     equimentSlotInfo1.setStatus(CardStatusEnum.ACTIVE);
                     equipmentInfoBiz.activeSolt(equimentSlotInfo1);
                     break;
                case SOLT_INFO: //卡槽消息 根据卡槽数量生成
                    log.info(">开始处理各卡槽信息消息{}",data);
                    String slotChannel = dataJson.getString("Channel");//哪一个通道
                    String slotIndex = dataJson.getString("SIM");//
                    String ccid1 = dataJson.getString("CCID");
                    String imei = dataJson.getString("COPS");
                    String simA = dataJson.getString("SIMA"); //卡槽A的状态，0：未插卡，1:SIM卡在位，2：SIM卡在位但时呼叫超限
                    String simB = dataJson.getString("SIMB"); //卡槽B的状态，0：未插卡，1:SIM卡在位，2：SIM卡在位但时呼叫超限
                    String simC = dataJson.getString("SIMC"); //卡槽C的状态，0：未插卡，1:SIM卡在位，2：SIM卡在位但时呼叫超限
                    String simD = dataJson.getString("SIMD"); //卡槽d的状态，0：未插卡，1:SIM卡在位，2：SIM卡在位但时呼叫超限

                    List<EquimentSlotInfo> equimentSlotInfoList =new ArrayList<EquimentSlotInfo>();
                    //卡槽1
                    if(simA!=null){
                        EquimentSlotInfo equimentSlotInfoA= this.createEquimentSlotInfo( sn, slotChannel,"1" ,ccid1, imei, simA );
                        equimentSlotInfoList.add(equimentSlotInfoA);
                    }

                    //卡槽2
                    if(simB!=null){
                        EquimentSlotInfo equimentSlotInfoB= this.createEquimentSlotInfo( sn, slotChannel, "2",ccid1, imei, simB );
                        equimentSlotInfoList.add(equimentSlotInfoB);
                    }
                    //卡槽3
                    if(simC!=null){
                        EquimentSlotInfo equimentSlotInfoC= this.createEquimentSlotInfo( sn, slotChannel, "3",ccid1, imei, simC );
                        equimentSlotInfoList.add(equimentSlotInfoC);
                    }

                    //卡槽3
                    if(simD!=null){
                        EquimentSlotInfo equimentSlotInfoD= this.createEquimentSlotInfo( sn, slotChannel, "4",ccid1, imei, simD );
                        equimentSlotInfoList.add(equimentSlotInfoD);
                    }
                    equipmentInfoBiz.createSoltInfo(equimentSlotInfoList);

                    break;
                case CALL_LIMIT: //呼叫达到次数通知
                    log.info(">开始处理呼叫达到次数通知消息{}",data);
                    String callLmitChannel = dataJson.getString("Channel");
                    String callLmitSlotId = dataJson.getString("SlotID");
                    String callLmitInfo = dataJson.getString("Info");
                    EquimentSlotInfo callLmitequimentSlotInfo = new EquimentSlotInfo();
                    callLmitequimentSlotInfo.setChannel(callLmitChannel);
                    callLmitequimentSlotInfo.setSlotId(callLmitSlotId);
                    callLmitequimentSlotInfo.setInfo(SwxCallLimitTypeEnum.fromStr(callLmitInfo));
                    callLmitequimentSlotInfo.setSn(sn);
                    equipmentInfoBiz.dealCallLimit(callLmitequimentSlotInfo);
                    break;
                case CHANNEL_TRUNK_STATUS: //通道状态,用于呼叫中途上报每个通道的中继状态
                    log.info(">开始处理freeswitch 呼叫中途上报每个通道的中继状态消息{}",data);
                    String channelName = dataJson.getString("TrunkName");
                    String status =  dataJson.getString("Status"); //通道状态，InUse，Unavailable，Idle，Busy
                    if(channelName==null||status==null)
                        break;
                    RedisData redisData = new RedisData();
                    redisData.setSn(sn);
                    redisData.setStatus(status);
                    redisData.setTrunkName(channelName);
                    equipmentInfoBiz.createRedisData(swxEquipmentControlProcess,redisData);

                    break;
                case FREESWITCH_TRUNK:// freeswitch 中继状态，用于重启时获取设备信息（SipAddr, SipPort, AuthUser），更新所需设备信息
                    log.info(">开始处理freeswitch 中继状态消息{}",data);
                    String sipAddr = dataJson.getString("SipAddr");
                    String sipPort = dataJson.getString("SipPort");
                    String authUser = dataJson.getString("AuthUser");
                    equipmentInfoBiz.updateFreeswitchInfo(sn,sipAddr,sipPort,authUser);
                    break;

                case CHANNEL_TRUNK:// 校验通道状态，跑job 的时候处理(定时paojob检查通道状态)
                    String trunkName = dataJson.getString("TrunkName");
                    String status1 = dataJson.getString("Status");
                    RedisData redisData1 = new RedisData();
                    redisData1.setSn(sn);
                    redisData1.setStatus(status1);
                    redisData1.setTrunkName(trunkName);
                    equipmentInfoBiz.checkQueueIdle(swxEquipmentControlProcess,redisData1);

                    break;
                default:
                    log.error(">>收到未进行处理的swx 设备消息：{}",data);
                    break;

            }
        }catch ( Exception e){
            log.error("======>>处理swx 设备消息异常",e);
            rs = "-1";
        }
        return rs;
    }

    private EquimentSlotInfo createEquimentSlotInfo(String sn,String slotChannel,String slotIndex,String ccid1,String imei,String sim ){
        EquimentSlotInfo equimentSlotInfo = new EquimentSlotInfo();
        equimentSlotInfo.setSn(sn);
        equimentSlotInfo.setChannel(slotChannel);
        equimentSlotInfo.setSlotId(slotIndex);
        equimentSlotInfo.setSlotState(SlotStateEnum.fromStr(sim));

        if(ccid1!=null&&!"n/a".equals(ccid1)){
            equimentSlotInfo.setCcid(ccid1);
        }
        if(imei!=null&&!"n/a".equals(imei)){
            equimentSlotInfo.setImsi(imei);
        }
        return equimentSlotInfo;

    }


}
